package cn.swpu.blog.controller;

import cn.swpu.blog.config.FtpConfig;
import cn.swpu.blog.util.FtpUtil;
import cn.swpu.blog.util.UploadUtil;
import cn.swpu.blog.vo.ResponseVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author 冰翔
 * @Date Created in 1:55 下午 2020/12/18
 */
@Api(tags = "文件上传")
@RestController
public class FileController {

    @Autowired
    private FtpConfig ftpConfig;

    @PreAuthorize("hasRole('ADMIN')")
    @ApiOperation("可以一次上传单张图片，或者多张图片")
    @PostMapping(value = "/uploadPicture", headers = "content-type=multipart/*")
    public ResponseVo<Map<String, List<String>>> uploadFile(@RequestParam("picture") MultipartFile[]  files) throws IOException {

        List<String> fileUrls = new ArrayList<>();
        for (MultipartFile file : files) {

            String picNewName = UploadUtil.generateRandomFileName(file.getOriginalFilename());

            String picSavePath = "/";
            String fileUrl = FtpUtil.pictureUploadByConfig(ftpConfig, picNewName, picSavePath, file.getInputStream());

            if (fileUrl != null) {
                fileUrls.add(fileUrl);
            }
        }

        Map<String, List<String>> response = new HashMap<>();
        response.put("urls", fileUrls);
        return ResponseVo.success(response);
    }
}
